package com.vip.base.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vip.base.service.ISysUserService;
import com.vip.common.constant.PublicConsts;
import com.vip.common.response.ErrorCode;
import com.vip.common.response.Result;
import com.vip.common.response.Results;
import com.vip.common.util.EmptyUtils;
import com.vip.common.util.MD5Utils;
import com.vip.database.dto.user.AddUserDTO;
import com.vip.database.dto.user.GetUserDTO;
import com.vip.database.entity.SysUser;
import com.vip.database.entity.SysUserRole;
import com.vip.database.mapper.SysUserMapper;
import com.vip.database.mapper.SysUserRoleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户表 服务实现类
 *
 * @author LEON
 * @since 2020-04-05
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private final SysUserMapper userMapper;
    private final SysUserRoleMapper userRoleMapper;

    /**
     * 命中率低，所以不采用缓存机制
     */
    @Override
    public Result<List<GetUserDTO>> getUserList(Integer pageNo, Integer pageSize, String account, String username) {
        try {
            PageHelper.startPage(pageNo, pageSize);
            List<GetUserDTO> result = userMapper.getUserList(EmptyUtils.removeBasicEmpty(account), EmptyUtils.removeBasicEmpty(username));
            PageInfo<GetUserDTO> pageInfo = new PageInfo<>(result);
            return Results.newSuccessResult(pageInfo.getList(), "查询成功", pageInfo.getTotal());
        } catch (Exception e) {
            log.error("获取用户列表数据出错！", e);
        }
        return Results.newFailResult(ErrorCode.DB_ERROR, "查询失败");
    }

    @Override
    public Result<String> userAccredit(String roleId, String userId, Boolean isAdd) {
        try {
            if (isAdd) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                if (userRoleMapper.insert(userRole) == 1) {
                    return Results.newSuccessResult(userId, "授权成功");
                }
            } else {
                if (userRoleMapper.deleteUserRoleOne(roleId, userId) > 0) {
                    return Results.newSuccessResult(userId, "撤权成功");
                }
            }

        } catch (Exception e) {
            log.error("用户授权出错", e);
        }
        if (isAdd) {
            return Results.newFailResult(ErrorCode.DB_ERROR, "授权失败");
        } else {
            return Results.newFailResult(ErrorCode.DB_ERROR, "撤权失败");
        }
    }

    @Override
    @Cacheable(value = "userCache", key = "'user_exist_' + #account")
    public Result<Boolean> userIsExist(String account) {
        try {
            // 如果查询结果为空则表示该账号不存在，否则存在
            if (userMapper.getUserIsExist(account)) {
                return Results.newSuccessResult(true, "该用户名已被注册，换个新的试试");
            } else {
                return Results.newSuccessResult(false);
            }
        } catch (Exception e) {
            log.error("查询用户出错", e);
        }
        return Results.newFailResult(ErrorCode.DB_ERROR, "查询失败");
    }

    @Override
    @Cacheable(value = "userCache", key = "'user_details_' + #id")
    public Result<GetUserDTO> getUserDetails(String id) {
        try {
            GetUserDTO user = userMapper.selectUserDetails(id);
            return Results.newSuccessResult(user, "查询成功");
        } catch (Exception e) {
            log.error("查询用户出错", e);
        }
        return Results.newFailResult(ErrorCode.DB_ERROR, "查询失败");
    }

    @Override
    public Result<String> addNewUser(AddUserDTO dto) {
        try {
            SysUser user = new SysUser();
            BeanUtils.copyProperties(dto, user);
            user.setPassword(MD5Utils.md5(dto.getPassword(), PublicConsts.SALT));
            if (userMapper.insert(user) > 0) {
                return Results.newSuccessResult(user.getId(), "添加成功");
            }
        } catch (Exception e) {
            log.error("新增用户出错", e);
        }
        return Results.newFailResult(ErrorCode.DB_ERROR, "添加失败");
    }

    @Override
    public Result<String> deleteUserById(String id) {
        try {
            if (userMapper.deleteById(id) == 1) {
                return Results.newSuccessResult(null, "删除成功");
            }
        } catch (Exception e) {
            log.error("删除用户出错", e);
        }
        return Results.newFailResult(ErrorCode.DB_ERROR, "删除失败");
    }

    @Override
    public Result<GetUserDTO> updateUser(String id, AddUserDTO dto) {
        try {
            SysUser user = new SysUser();
            BeanUtils.copyProperties(dto, user);
            user.setPassword(MD5Utils.md5(dto.getPassword(), PublicConsts.SALT)).setId(id);
            if (userMapper.updateById(user) == 1) {
                return Results.newSuccessResult(userMapper.selectUserDetails(id), "更新成功");
            } else {
                return Results.newFailResult(ErrorCode.DB_ERROR, "信息未更改");
            }
        } catch (Exception e) {
            log.error("更新用户出错", e);
        }
        return Results.newFailResult(ErrorCode.DB_ERROR, "更新失败");
    }

}
